﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using DocumentMaking.FluentNext.Dialogs;
using DocumentMaking.FluentNext.ViewModels;
using DocumentMaking.Lib.Models;
using DocumentMaking.Lib.Services;
using DynamicData;
using FluentAvalonia.UI.Controls;

namespace DocumentMaking.FluentNext.Themes;

public partial class SettingThemeView : UserControl
{
    public SettingThemeView()
    {
        InitializeComponent();
    }

    private void RemoveFileItemClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not SourceFileModel file) return;
        if (DataContext is not DocumentMakingViewModel model) return;
        model.Remove(file);
    }

    private void RemoveMemberClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not MemberModel member) return;
        if (DataContext is not DocumentMakingViewModel model) return;
        model.RemoveMember(member);
    }

    private async void AddMemberDataClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        if (top == null) return;

        try
        {
            var result = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions());
            if (result.Count == 0) return;
            if (DataContext is not DocumentMakingViewModel model) return;
            var single = result[0];
            var ext = Path.GetExtension(single.Path.LocalPath);
            switch (ext)
            {
                case ".json":
                    var s = await new StreamReader(await single.OpenReadAsync()).ReadToEndAsync();
                    if (string.IsNullOrEmpty(s)) return;
                    var array = JsonSerializer.Deserialize(s,
                        Lib.JsonContexts.MemberListContext.Default.MemberModelArray);
                    if (array == null) return;
                    model.Members.Add(array);
                    break;
                case ".xlsx" or ".xls":
                    var data = ExcelService.GetExcelList(await single.OpenReadAsync());
                    var models = ExcelService.DataTableToList<MemberModel>(data);
                    model.Members.Add(models);
                    break;
            }
        }
        catch (Exception exception)
        {
            var td = new TaskDialog
            {
                Title = "文档生成工具",
                Content = exception.ToString(),
                FooterVisibility = TaskDialogFooterVisibility.Never,
                Buttons =
                {
                    new TaskDialogButton("复制", true),
                    new TaskDialogButton("返回", false)
                },
                XamlRoot = (Visual)VisualRoot!
            };
            td.Closing += (dialog, args) =>
            {
                if (!(bool)args.Result) return;
                if (dialog.Content is not string s) return;
                TopLevel.GetTopLevel(this)!.Clipboard?.SetTextAsync(s);
            };
            await td.ShowAsync();
        }
    }

    private async void AddMemberClick(object? sender, RoutedEventArgs e)
    {
        var td = new TaskDialog
        {
            Title = "文档生成工具",
            Content = new AddMemberDialog(),
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Buttons =
            {
                TaskDialogButton.OKButton,
                TaskDialogButton.CancelButton
            },
            XamlRoot = (Visual)VisualRoot!
        };
        td.Closing += (dialog, args) =>
        {
            if ((TaskDialogStandardResult)args.Result != TaskDialogStandardResult.OK) return;
            if (dialog.Content is not AddMemberDialog d) return;
            var result = d.Done();
            if (result == null)
            {
                args.Cancel = false;
                return;
            }

            if (DataContext is not DocumentMakingViewModel model) return;
            model.Members.Add(result);
        };
        await td.ShowAsync();
    }

    private async void MemberInfoClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not MemberModel model) return;
        var td = new TaskDialog
        {
            Title = "文档生成工具",
            Content = new MemberInfoDialog(model),
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Buttons =
            {
                TaskDialogButton.OKButton,
                TaskDialogButton.CancelButton
            },
            XamlRoot = (Visual)VisualRoot!
        };
        await td.ShowAsync();
    }

    private void FileInfoClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not SourceFileModel model) return;
        Process.Start(new ProcessStartInfo() { FileName = model.FilePath, UseShellExecute = true });
    }

    private async void AddIgnoreClick(object? sender, RoutedEventArgs e)
    {
        if(DataContext is not DocumentMakingViewModel model)return;
        IgBorder.IsVisible = await model.AddIgnore() || model.Ignore.IgnoreList.Length > 0;
    }

    private async void DoneClick(object? sender, RoutedEventArgs e)
    {
        DocMakingBlock.Text = "正在生成中...";
        if(DataContext is not DocumentMakingViewModel model)return;
        var b = await model.Done();
        DocMakingBlock.Text = "生成文档";
        DoneBar.Message = b;
        if (b.StartsWith("成功"))
            DoneBar.Severity = InfoBarSeverity.Success;
        else if (b == "信息未填完")
            DoneBar.Severity = InfoBarSeverity.Warning;
        else
            DoneBar.Severity = InfoBarSeverity.Error;
        DoneBar.IsOpen = true;
    }

    private void ReRunClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not DocumentMakingViewModel model) return;
        model.Clear();
        MainPanel.IsVisible = true;
        OtherPanel.IsVisible = false;
    }

    private void ExitClick(object? sender, RoutedEventArgs e)
    {
        MainPanel.IsVisible = false;
        OtherPanel.IsVisible = true;
    }
    
    private void DeleteClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not DocumentMakingViewModel model) return;
        model.Clear();
    }

    private async void OpenDataClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        if (top == null) return;

        var result = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions());
        if (result.Count == 0) return;
        if (DataContext is not DocumentMakingViewModel model) return;
        var single = result[0];
        var s = await new StreamReader(await single.OpenReadAsync()).ReadToEndAsync();
        if (string.IsNullOrEmpty(s)) return;
        var data = JsonSerializer.Deserialize(s, Lib.JsonContexts.InfoContext.Default.DataModel);
        if (data == null) return;
        model.Init(data);
    }
}